//
//  CJExten+StrCode.swift
//  CJCore
//
//  Created by 陈警卫 on 2024-06-14.
//

import Foundation
import CommonCrypto

public extension String {
    
    /// MD5
    @available(iOS, introduced: 2.0, deprecated: 13.0, message: "This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).")
    var cj_md5: String? {
        let value = self.cString(using: .utf8)
        let valuelen = CUnsignedInt(lengthOfBytes(using: .utf8))
        let digestlen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestlen)
        guard let value = value else { return nil }
        CC_MD5(value, valuelen, result)
        
        let hash = NSMutableString()
        for i in 0..<digestlen {
            hash.appendFormat("%02x", result[i])
        }
        result.deallocate()
        return hash as String
    }
    
    /// base64编码
    var cj_base64Encode: String {
        guard let data = self.data(using: .utf8) else { return "" }
        return data.base64EncodedString()
    }
    
    /// base64解码
    var cj_base64Decode: String {
        guard let data = Data(base64Encoded: self, options: .ignoreUnknownCharacters) else { return "" }
        return String(data: data, encoding: .utf8) ?? ""
    }
    
    /// URL编码
    var cj_urlEncode: String {
        guard let value = self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return "" }
        return value
    }
    
    /// URL编码
    var cj_urlEncodeURL: URL? {
        let value = self.cj_urlEncode
        let url = URL(string: value)
        return url
    }
    
    /// URL解码
    func cj_urlDecode() -> String {
        return self.removingPercentEncoding ?? ""
    }
}
